package uscdb.task;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import uscdb.model.Tlogic;
import uscdb.pageModel.GlobalData;

@Component
public class SearchEnginesTask {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SearchEnginesTask.class);

	@Autowired
	private SessionFactory sessionFactory;

	GlobalData globalData = GlobalData.getInstane();

	// 每30分钟执行一次
	@Scheduled(cron = "0 0/30 *  * * ?")
	public void updateIndex() {
		// 这个对象的作用是，记录出问题的对象
		Tlogic tlogicLog = new Tlogic();
		try {

			if (!globalData.isUpdatingIndex()) {
				globalData.setUPDATEINDEX(true);
				logger.info("开始更新Lucene索引");
				Session session = sessionFactory.getCurrentSession();
				FullTextSession fullTextSession = Search.getFullTextSession(session);
				@SuppressWarnings("unchecked")
				List<Tlogic> tlogics = session.createQuery("from Tlogic").list();
				for (Tlogic tlogic : tlogics) {
					// 记录当时的tlogic
					tlogicLog = tlogic;
					fullTextSession.index(tlogic);
				}
				globalData.setUPDATEINDEX(false);
				logger.info("完毕更新Lucene索引");
			} else {
				logger.info("正在更新Lucene索引");
			}
		} catch (Exception e) {
			globalData.setUPDATEINDEX(false);
			logger.error("The error tlogic is : " + tlogicLog.toString());
			logger.error(e.getMessage(), e);
		}

	}
}
